/**
 * @file led_module.c
 * @author Jason Wen (embediot@163.com)
 * @brief 通用的LED显示模块
 * @version 0.1
 * @date 2024-06-15
 * 
 * @copyright EmbedIoT Studio Copyright (c) 2024
 * 
 */

#include "led_module.h"
#include "stddef.h"
#include "string.h"

//定义一个LED模块实例
led_module_t led_module = 
{
    .led_count = 0,
    .led_drv = NULL,
};

//初始化LED模块
static int _init(struct led_module *_this)
{
    int ret = 0;

    if(NULL == _this)return -1;

    led_module_t *m = (led_module_t *)_this;

    if(NULL != led_module.led_drv)
    {
        led_module.led_drv->init(led_module.led_drv);    //初始化LED驱动
    }

    return ret;
}

//启动LED模块状态机
static int _start(struct led_module *_this)
{
	int ret = 0;
    if(NULL == _this)return -1;
	
    //在这里添加某些启动条件，也可以不添加

	return ret;
}

//LED模块状态机处理函数
static int _handler(struct led_module *_this)
{
	int ret = 0;
    if(NULL == _this)return -1;
	
    static unsigned int count = 0;
    static unsigned char flag = 0;

    if(count++ < 1000)return 0;
    count = 0;

    //在这里完善led模块的状态机（TODO）

    //每隔1秒，翻转指定的LED（演示作用）
    _this->led_drv->toggle(_this->led_drv, LED_ID_1);
    _this->led_drv->toggle(_this->led_drv, LED_ID_2);
    _this->led_drv->toggle(_this->led_drv, LED_ID_3);
    _this->led_drv->toggle(_this->led_drv, LED_ID_4);

	return ret;
}

//获取LED硬件数量
static int _get_led_count(struct led_module *_this)
{
    if(NULL == _this)return -1;

    _this->led_count = _this->led_drv->led_count;
	
	return _this->led_count;
}

/**
 * @brief 创建一个LED模块
 * 
 * @param _this LED模块句柄
 * @param cfg 配置信息结构体
 * @return led_module_t* 
 */
led_module_t *led_module_create(struct led_module *_this, led_module_cfg_t *cfg)
{
    if(NULL == cfg)return NULL;

    led_module.init = _init;
    led_module.start = _start;
    led_module.handler = _handler;
    led_module.get_led_count = _get_led_count;

    //使用简单工厂模式，初始化led驱动
    if(strcmp("PIN", cfg->drv_name) == 0)
    {
        led_module.led_drv = (led_driver_t*)led_drv_pin_create();
    }
    else if (strcmp("PWM", cfg->drv_name) == 0)
    {
        led_module.led_drv = (led_driver_t*)led_drv_pwm_create();
    }
    else if(strcmp("WS2812B", cfg->drv_name) == 0)
    {
        led_module.led_drv = (led_driver_t*)led_drv_ws2812b_create();
    }
    else
    {
        led_module.led_drv = NULL;
    }

    return &led_module;
}



